import redis
from flask import *
from db import db
import datetime, random, time
from flask import current_app as app,request
from utils.mysms import SmsCode
from flask_restful import Api, Resource, reqparse
from utils.myjwt import MyJwt


user_blue = Blueprint('user',__name__)
api = Api(user_blue)

@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    app.logger.error(str)
    app.logger.info('info log')
    app.logger.warning('warning log')

    sql = "insert into user values(0,'aa22222','abc')"
    db.update(sql)
    db.commit()
    sql1 = "select * from user"
    res = db.find_all(sql1)
    print(res)
    return 'ok234234'



# 发送验证码的函数
def smscode(mobile, code):
    from app import app
    with app.app_context():
        SmsCode().sms_code(mobile, code)


# 发送短信验证码
@user_blue.route('/sms/<mobile>')
def sms_code(mobile):
    code = str(random.randint(0,9))
    current_app.schedul.add_job(smscode, args=[mobile, code])

    return jsonify({'code': 200, 'msg': '发送成功，请注意查收'})


# 登录
class UserView(Resource):
    def post(self):
        # 获取参数
        req = reqparse.RequestParser()
        req.add_argument('mobile', required=True)
        req.add_argument('sms_code', required=True)
        args = req.parse_args()
        mobile = args['mobile']

        # 判断数据是否为空
        if not all([args['mobile'], args['sms_code']]):
            return jsonify({'code': 400, 'msg': '数据不能为空'})

        # 判断验证码
        pool = redis.ConnectionPool()
        r = redis.Redis(connection_pool=pool)
        mobile_get = r.get(mobile)

        # 判断是否过期或不一致
        if not mobile_get or args['sms_code'] != mobile_get.decode():
            return jsonify({'code': 400, 'msg': '验证码过期或不一致'})

        # 判断用户是否存在
        sql = f'select * from user where phone={mobile}'
        user_info = db.find(sql)
        if not user_info:
            # 注册
            # 插入到数据库
            sqll = f'insert into user(name, phone) values("游客{mobile[-4:]}", {mobile})'
            db.update(sqll)
            db.commit()

        sql = f'select * from user where phone={mobile}'
        user_info = db.find(sql)
        # 生成token
        token = MyJwt().jwt_encode({
            'id': user_info['id'],
            'name': user_info['name'],
            'mobile': user_info['phone'],
            'exp': int(time.time()) + 3600*24*15
        })

        return jsonify({'code': 200, 'msg':'登录成功', 'token': token})


api.add_resource(UserView, '/user')


